﻿using Manon.Core.Commons;
using Manon.Core.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;

namespace Manon.Core.Filters
{
    /// <summary>
    /// 给api返回结果包一层状态码
    /// </summary>
    public class ApiResultFilter : IResultFilter
    {

        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result == null) return;

            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                var errMsg = modelState.Values.SelectMany(x => x.Errors?.Select(y => y.ErrorMessage) ?? new List<string>());

                context.Result = new JsonResult(new ApiResult()
                {
                    Success = false,
                    StatusCode = StateCode.Error.GetHashCode(),
                    Message = String.Join(";", errMsg)
                }); 
                // 如果模型验证的时候直接返回
                return;
            }

            if (context.Result is ObjectResult objectResult)
            {
                context.Result = new JsonResult(ApiResult.SuccessResult(context, objectResult.Value));
            }
            else if (context.Result is JsonResult jsonResult)
            {
                context.Result = new JsonResult(ApiResult.SuccessResult(context, jsonResult.Value));
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new JsonResult(new ApiResult()
                {
                    StatusCode = StateCode.NotFound.GetHashCode(),
                    Message = "未找到资源"
                });
            }
        }

        public void OnResultExecuted(ResultExecutedContext context)
        {
        }


    }
}


//if (objectResult.DeclaredType is null) 
//{
//    context.Result = new JsonResult(new
//    {
//        StatusCode = objectResult.StatusCode,
//        Data = objectResult.Value,
//        Exception = "",
//        Message = "请求成功",
//        Path = path,
//        Timestamp = timestamp
//    });
//}
//else 
//{
//    context.Result = new JsonResult(ApiResult.SuccessResult(context, objectResult.Value));
//}